<template lang="html">
  <el-dialog
    title="配置功能权限"
    width="500px"
    :close-on-click-modal="false"
    :visible="dialogVisible"
    destroy-on-close
    class="func-auth-draw"
    @close="close"
  >
    <div v-loading="wrapperLoading" class="dialog-wrapper">
      <!-- <div class="mb5" flex="dir:right">
        <el-checkbox
          v-model="fullFuncPermissions"
          @change="fullFuncPermissionsChange"
          >全部功能权限</el-checkbox
        >
      </div> -->

      <el-table :data="affiliationAppOptions" border style="width: 100%" stripe>
        <el-table-column prop="name" label="应用名称" width="150" align="center" />
        <el-table-column prop="type" label="功能权限" align="center">
          <template slot-scope="{ row }">
            <el-radio-group v-model="row.type" @change="radioChange">
              <el-radio
                v-for="(item, index) in funcPermissionTypeOptions"
                :key="index"
                :label="item.value"
                :class="{
                  'last-radio': index === funcPermissionTypeOptions.length - 1,
                }"
                >{{ item.name }}</el-radio
              >
              <el-button v-if="row.type === '2'" type="text" @click="doModify(row)">修改</el-button>
            </el-radio-group>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <span slot="footer">
      <el-button @click="close">取消</el-button>
      <el-button type="primary" :loading="btnLoading" @click="submitData">确定</el-button>
    </span>

    <!-- 权限配置弹窗开关 -->
    <func-auth-tree-draw
      :dialogVisible.sync="funcAuthTreeDrawVisible"
      :currentRowObj="currentRowObj"
      :currentAppObj="currentAppObj"
      @success="funcAuthCheckedSuccess"
    />
  </el-dialog>
</template>

<script>
import dialogMixin from "mixins/dialogMixin";
import FuncAuthTreeDraw from "./components/func-auth-tree-draw";
import { DictKeys } from "api/sys/dict";
import { RoleMenuPermBatch, RoleMenuPerm } from "api/sys/role";

export default {
  components: { FuncAuthTreeDraw },
  mixins: [dialogMixin],
  props: {
    // 当前行数据
    currentRowObj: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      // 功能权限配置开关
      funcAuthTreeDrawVisible: false,
      // 应用配置文件
      affiliationAppOptions: [],
      // 功能权限配置文件
      funcPermissionTypeOptions: [],
      // 全部功能权限
      fullFuncPermissions: false,
      // 当前所属应用信息
      currentAppObj: null,
    };
  },
  methods: {
    /**
     * 初始化
     */
    async initForm() {
      try {
        this.wrapperLoading = true;
        const [roleMenuData, dictKeysData] = await Promise.all([
          this._RoleMenuPerm(),
          this._DictKeys(),
        ]);
        this.dictKeysFormat({ dictKeysData, detailArr: roleMenuData });
        this.setFullFuncPermissions();
      } catch (e) {
        console.log(e);
      } finally {
        this.wrapperLoading = false;
      }
    },
    /**
     * 提交
     */
    async submitData() {
      try {
        this.btnLoading = true;
        await RoleMenuPermBatch(this.getSubmitParams());
        this.$message.success("功能权限配置成功");
        this.$emit("success");
        this.close();
      } catch (e) {
        console.log(e);
      } finally {
        this.btnLoading = false;
      }
    },
    /**
     * 修改
     */
    doModify(row) {
      this.currentAppObj = row;
      this.funcAuthTreeDrawVisible = true;
    },
    /**
     * 获取详情
     */
    async _RoleMenuPerm() {
      try {
        const data = await RoleMenuPerm(this.currentRowObj.id);
        return data;
      } catch (e) {
        console.log(e);
      }
    },
    /**
     * 获取数据字典
     */
    async _DictKeys() {
      try {
        const tempArr = ["affiliation_app", "func_permission_type"];
        const data = await DictKeys(tempArr.join());
        return data;
      } catch (e) {
        console.log(e);
      }
    },
    /**
     * 数据字典数据格式化
     */
    dictKeysFormat({ dictKeysData, detailArr }) {
      if (dictKeysData) {
        const { affiliation_app: affiliationApp, func_permission_type: funcPermissionType } =
          dictKeysData;
        this.affiliationAppOptions = this.affiliationAppFormat({
          affiliationApp,
          detailArr,
        });
        this.funcPermissionTypeOptions = funcPermissionType;
      }
    },
    /**
     * 应用分类数据格式化
     */
    affiliationAppFormat({ affiliationApp, detailArr }) {
      affiliationApp.map((item) => {
        const tempObj = detailArr.find((item1) => item1.affiliationApp === item.value);
        item.roleMenuList = [];
        if (tempObj) {
          const { type, affiliationAppTypeList, roleMenuList } = tempObj;
          item.type = type;
          if (type === "2") {
            item.roleMenuList = roleMenuList;
            item.affiliationAppTypeList = affiliationAppTypeList;
          }
        } else {
          item.type = "0";
        }
      });
      return affiliationApp;
    },
    radioChange() {
      this.setFullFuncPermissions();
    },
    /**
     * 设置全部功能权限的值
     */
    setFullFuncPermissions() {
      const tempArr = this.affiliationAppOptions.filter((item) => item.type === "1");
      this.fullFuncPermissions = tempArr.length === this.affiliationAppOptions.length;
    },
    /**
     * 全部功能权限选择事件
     */
    fullFuncPermissionsChange(val) {
      this.affiliationAppOptions.map((item) => {
        item.type = val ? "1" : "";
      });
    },
    /**
     * 功能权限分配成功的回调
     */
    funcAuthCheckedSuccess(val) {
      const {
        roleMenuPermList: { roleMenuList, affiliationAppTypeList },
        affiliationApp,
      } = val;
      this.affiliationAppOptions.map((item) => {
        if (item.value === affiliationApp) {
          item.roleMenuList = roleMenuList;
          item.affiliationAppTypeList = affiliationAppTypeList;
        }
      });
    },
    /**
     * 获取提交参数
     */
    getSubmitParams() {
      const { id } = this.currentRowObj;
      let roleMenuPermList = [];
      this.affiliationAppOptions.map((item) => {
        const { name, value, roleMenuList, type, affiliationAppTypeList } = item;
        roleMenuPermList.push({
          ...(type === "2" && { roleMenuList, affiliationAppTypeList }),
          affiliationApp: value,
          affiliationAppName: name,
          type,
        });
      });
      return {
        id,
        roleMenuPermList,
      };
    },
  },
};
</script>

<style lang="scss" scoped>
.func-auth-draw {
  .last-radio {
    margin-right: 15px !important;
  }
}
</style>
